/*
 * 批量回填 page_views 集合中的 UA / customData 字段
 * - 解析 userAgent -> browser / os / device
 * - 从 customData 计算 screenSize / language
 *
 * 运行方式（在 devops-server 目录下）：
 *   pnpm script:backfill-pageview-ua
 */

const { MongoClient } = require('mongodb');
const UAParser = require('ua-parser-js');
const dotenv = require('dotenv');
const path = require('path');

// 尝试加载 .env.local 或 .env
dotenv.config({ path: path.join(__dirname, '..', '.env.local') });
dotenv.config({ path: path.join(__dirname, '..', '.env') });

const MONGO_HOST = process.env.MONGO_HOST || 'localhost';
const MONGO_PORT = process.env.MONGO_PORT || 27017;
const MONGO_DATABASE = process.env.MONGO_DATABASE || 'tracker';
const MONGO_USERNAME = process.env.MONGO_USERNAME || '';
const MONGO_PASSWORD = process.env.MONGO_PASSWORD || '';

function buildMongoUri() {
  if (MONGO_USERNAME && MONGO_PASSWORD) {
    return `mongodb://${encodeURIComponent(MONGO_USERNAME)}:${encodeURIComponent(MONGO_PASSWORD)}@${MONGO_HOST}:${MONGO_PORT}/${MONGO_DATABASE}?authSource=${MONGO_DATABASE}`;
  }
  return `mongodb://${MONGO_HOST}:${MONGO_PORT}/${MONGO_DATABASE}`;
}

async function run() {
  const uri = buildMongoUri();
  console.log('🔗 Connecting to MongoDB:', uri.replace(/:[^:@/]+@/, ':******@'));

  const client = new MongoClient(uri);

  try {
    await client.connect();
    const db = client.db(MONGO_DATABASE);
    const collection = db.collection('page_views');

    const total = await collection.countDocuments();
    console.log(`📊 Total page_views documents: ${total}`);

    const batchSize = 500;
    let processed = 0;

    const cursor = collection.find({}, { batchSize });

    while (await cursor.hasNext()) {
      const doc = await cursor.next();
      processed++;

      const updates = {};
      const userAgent = doc.userAgent || '';

      // 解析 UA
      try {
        if (userAgent) {
          const parser = new UAParser(userAgent);
          const result = parser.getResult();
          if (result.browser && result.browser.name) {
            updates.browser = result.browser.name;
          }
          if (result.os && result.os.name) {
            updates.os = result.os.name;
          }
          if (result.device && result.device.type) {
            updates.device = result.device.type;
          }
        }
      } catch (e) {
        console.warn(`UA parse failed for _id=${doc._id}:`, e.message);
      }

      // 从 customData 推导 screenSize / language
      const custom = doc.customData || {};
      if (custom.screenWidth && custom.screenHeight) {
        updates.screenSize = `${custom.screenWidth}x${custom.screenHeight}`;
      }
      if (custom.language) {
        updates.language = custom.language;
      }

      // country / city 目前无法从 UA 可靠解析，这里只保留已有值

      if (Object.keys(updates).length > 0) {
        await collection.updateOne(
          { _id: doc._id },
          { $set: updates }
        );
      }

      if (processed % 1000 === 0 || processed === total) {
        console.log(`✅ Processed ${processed}/${total}`);
      }
    }

    console.log('🎉 Backfill finished.');
  } catch (err) {
    console.error('❌ Backfill error:', err);
    process.exitCode = 1;
  } finally {
    await client.close();
  }
}

run();
